<template>
  <div>
    <TableSearch
      ref="tableSearch"
      :search-path="searchPath"
      :columns="columns"
      :tableData="tableData"
      :tableBtns="tableBtns"
      :form="form"
      :formItemsInline="formItemsInline"
      :span-method="objectSpanMethod"
      @handleTableData="handleTableData"
      @reset="reset"
    >
      <template slot="address">
        <el-form-item>
          <HycAddressCascader ref="area" v-model="area" />
        </el-form-item>
      </template>
      <template slot="date">
        <el-form-item>
          <SearchDatePicker
            :start.sync="form.startTime"
            :end.sync="form.endTime"
          />
        </el-form-item>
      </template>
      <template slot="alarmType">
        <el-form-item>
          <el-select v-model="alarmType" placeholder="告警类型">
            <el-option
              v-for="item in alarmTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </template>
      <el-table-column label="所属电站" slot="stationName">
        <template #default="{ row }">
          <router-link
            :to="{
              name: 'StationDetail',
              params: { id: row.stationId },
              query: { type: 'ZTSocket' },
            }"
            >{{ row.stationName }}</router-link
          >
        </template>
      </el-table-column>
    </TableSearch>
    <EditDeviceThreshold
      @refreshTable="refreshTable"
      :visible.sync="editDeviceThresholdVisible"
      :option-attr="optionAttr"
    />
    <ViewDevice
      @refreshTable="refreshTable"
      :visible.sync="viewDeviceVisible"
      :type="viewDeviceType"
      :option-attr="optionAttr"
    />
    <BatchUpload
      v-if="batchUploadVisible"
      :visible.sync="batchUploadVisible"
      @refreshTable="refreshTable"
      :dialog-type="dialogType"
    ></BatchUpload>
    <PortsListForCentralSocket
      :visible.sync="viewPortsListVisible"
      :portsList="portsList"
    >
    </PortsListForCentralSocket>

    <TimeSelectionDialog
      v-if="timeSelectionModal"
      :portsList="portsList"
      :visible.sync="timeSelectionModal"
      @refresh="refreshTable"
    />

    <CommandSend ref="commandSend" />

    <el-dialog
      title="告警日志"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div>
        {{ alarmDetail }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import TableSearch from '@/components/TableSearch'
import SearchDatePicker from '@/components/SearchDatePicker'
import HycAddressCascader from '@/components/hycAddressCascader'
import EditDeviceThreshold from './EditDeviceThreshold'
import ViewDevice from './ViewDevice'
import BatchUpload from './BatchUpload'
import PortsListForCentralSocket from './PortsListForCentralSocket'
import TimeSelectionDialog from '@/components/timeSelectionDialog'
import CommandSend from './CommandSend.vue'
import {
  alarmType,
  selfCheck,
  resetDevice,
  deviceVersionUp,
  deviceToExcel,
  resetCreateTime,
  deviceAlarmList,
} from '@/api/device'
import { typeMap } from '@/utils/format'
import formatter from '@/utils/format'
export default {
  name: 'GatewayTable',
  components: {
    TableSearch,
    SearchDatePicker,
    HycAddressCascader,
    EditDeviceThreshold,
    ViewDevice,
    BatchUpload,
    PortsListForCentralSocket,
    TimeSelectionDialog,
    CommandSend,
  },
  data() {
    return {
      form: {
        city: null,
        district: null,
        province: null,
        deviceStatus: 'ALL',
      },
      tableData: {},
      area: {},
      optionAttr: {},
      portsList: {},
      searchPath: '/web/device-management/device-management/查询',
      batchUploadVisible: false,
      editDeviceThresholdVisible: false,
      viewDeviceVisible: false,
      viewDeviceType: '',
      viewPortsListVisible: false,
      timeSelectionModal: false,
      tableBtns: [
        {
          label: 'Excel批量注销',
          click: () => this.handleBatchUpload('ADMIN_LOGOUT'),
          icon: 'el-icon-delete',
          type: 'warning',
          resourceId: '/web/device-management/device-management/Excel批量注销',
        },
        {
          label: '(批量注销模板下载)',
          isDownload: true,
          href: require('../../../assets/batchTemplate/批量注销设备模板.xlsx'),
          fileName: '批量注销设备模板',
          resourceId:
            '/web/device-management/device-management/批量注销模板下载',
        },
        {
          label: '导出',
          isExport: true,
          startDownload: (callback) => {
            let params = Object.assign({}, this.form, this.area)
            params.deviceStatus === 'ALL' && delete params.deviceStatus
            deviceToExcel({
              ...params,
              currentPage: 1,
              deviceType: this.$attrs.type,
              pageSize: 10,
            })
              .then((res) => {
                callback(res)
              })
              .catch((err) => {
                console.log(err)
                callback(0)
              })
          },
          resourceId: '/web/device-management/device-management/导出',
        },
      ],
      formItemsInline: [
        {
          type: 'text',
          value: 'deviceId',
          placeholder: '请输入设备号',
          clearable: true,
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          type: 'text',
          value: 'stationName',
          placeholder: '请输入所属电站',
          clearable: true,
          resourceId: '/web/device-management/device-management/所属电站',
        },
        {
          type: 'text',
          value: 'mchName',
          placeholder: '请输入所属运营商',
          clearable: true,
          resourceId: '/web/device-management/device-management/所属运营商',
        },
        {
          type: 'text',
          value: 'versionNum',
          placeholder: '请输入版本号',
          clearable: true,
          ifRender: () => {
            return (
              this.$attrs.type === 'GATEWAY' ||
              this.$attrs.type === 'CENTRAL_SOCKET'
            )
          },
          resourceId: '/web/device-management/device-management/设备版本号',
        },
        {
          slot: 'address',
        },
        {
          slot: 'date',
        },
        {
          type: 'text',
          value: 'coupletCard',
          placeholder: '请输入物联卡号',
          clearable: true,
          ifRender: () => {
            return (
              this.$attrs.type === 'GATEWAY' ||
              this.$attrs.type === 'CENTRAL_SOCKET'
            )
          },
        },
        {
          type: 'select',
          value: 'gatewayType',
          placeholder: '网关类型',
          clearable: true,
          options: typeMap.selectOptions(
            ['ADMIN', 'SELF_OPERATION_ADMIN', 'NORMAL_USER'],
            'gatewayType'
          ),
          ifRender: () => {
            return (
              this.$attrs.type === 'GATEWAY' ||
              this.$attrs.type === 'CENTRAL_SOCKET'
            )
          },
          resourceId: '/web/device-management/device-management/设备类型',
        },
        {
          slot: 'alarmType',
        },
        {
          type: 'select',
          value: 'socketId',
          placeholder: '端口号',
          clearable: true,
          options: [
            { label: 1, value: 1 },
            { label: 2, value: 2 },
          ],
          resourceId: '/web/device-management/device-management/设备号',
        },
      ],
      columns: [
        {
          label: '设备号',
          prop: 'deviceId',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '设备端口号',
          prop: 'socketId',
          width: 120,
          resourceId: '/web/device-management/device-management/设备号',
        },

        {
          label: '注册状态',
          prop: 'activeDate',
          resourceId: '/web/device-management/device-management/设备号',
          formatter: (row) => {
            return row.activeDate ? '已注册' : '未注册'
          },
        },
        {
          slot: 'stationName',
          width: 240,
          resourceId: '/web/device-management/device-management/所属电站',
        },
        {
          label: '所属位置',
          prop: 'stationAddress',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '所属运营商',
          prop: 'merchantName',
          width: 120,
          resourceId: '/web/device-management/device-management/所属运营商',
        },
        {
          label: '告警时间',
          prop: 'alarmTime',
          resourceId: '/web/device-management/device-management/添加时间',
        },
        {
          label: '告警类型',
          prop: 'alarmTypeName',
          width: 200,
          resourceId: '/web/device-management/device-management/状态',
        },

        {
          label: '操作',
          resourceId: '/web/device-management/device-management/操作',
          buttons: [
            {
              label: '查看',
              resourceId: '/web/device-management/device-management/复位',
              click: this.handleDetail,
            },
          ],
        },
      ],
      alarmTypeOptions: [],
      dialogVisible: false,
      alarmDetail: '',
    }
  },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
    userId() {
      return this.$store.getters.userId
    },
  },
  methods: {
    //修改日期
    alertAddTime() {
      this.timeSelectionModal = true
    },

    //恢复添加日期
    recoverAddTime(row) {
      this.$confirm(`确认恢复修改前的日期？`, '恢复日期', {
        center: true,
        customClass: 'tip-dialog__wrapper',
      })
        .then(() => {
          resetCreateTime({
            deviceId: row.deviceId,
          }).then(() => {
            this.$message({
              message: '恢复成功',
              type: 'success',
            })
            this.refreshTable()
          })
        })
        .catch((err) => console.log(err))
    },

    reset() {
      this.form = {
        deviceStatus: 'ALL',
      }
      this.area = {}
    },
    handleBatchUpload(type) {
      this.batchUploadVisible = true
      this.dialogType = type
    },
    objectSpanMethod({ row, column }) {
      if (
        this.$attrs.type === 'GATEWAY' ||
        this.$attrs.type === 'CENTRAL_SOCKET' ||
        this.$attrs.type === 'ZT_SOCKET'
      ) {
        return
      }
      if (
        (column.label !== '状态' &&
          column.label !== '操作' &&
          column.label !== '端口号') ||
        (column.label === '操作' &&
          !this.resourceSet.includes(
            '/web/device-management/device-management/自检'
          ))
      ) {
        return {
          rowspan: row.socketLength,
          colspan: 1,
        }
      }
    },
    handleSocket(arr) {
      let list = []
      arr.forEach((item) => {
        let sockets = item.sockets || []
        sockets.forEach((socket, index) => {
          list.push({
            socketId: socket.socketId,
            socketStatus: socket.socketStatus,
            socketLength: index === 0 ? sockets.length : 0,
            ...item,
          })
        })
      })
      return list
    },
    handleDetail(row) {
      this.dialogVisible = true
      this.alarmDetail = JSON.parse(row.details)
    },
    handleUpgrade(row) {
      const loading = this.$loading({
        lock: true,
        text: '操作进行中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      })
      deviceVersionUp({ batchTimeout: 30, deviceId: row.deviceId }).then(
        () => {
          loading.close()
          this.$message({
            type: 'success',
            message: '指令下发成功，跳转升级结果页面',
          })
          this.$router.push('/device/upgrade')
        },
        () => {
          loading.close()
        }
      )
    },
    handleTableData(params) {
      if (params.deviceStatus === 'ALL') {
        delete params.deviceStatus
      }
      params = { ...params, ...this.area }

      deviceAlarmList(params).then((res) => {
        console.log(res)
        this.tableData = {
          list: res.records,
          totalCount: res.total,
        }
      })

      alarmType().then((res) => {
        console.log(res)
        this.alarmTypeOptions = res.map((item) => {
          return {
            label: item.desc,
            value: item.code,
          }
        })
      })
    },
    refreshTable() {
      console.log(11111)
      this.$refs['tableSearch'].refreshTable()
    },
  },
}
</script>
